package com.hisan.freeride.home.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.hisan.freeride.R;
import com.hisan.freeride.common.base.AppConfig;
import com.hisan.freeride.common.base.BaseActivity;
import com.hisan.freeride.common.callback.DialogCallback;
import com.hisan.freeride.common.service.ContactInfoService;
import com.hisan.freeride.common.utils.CollectionUtils;
import com.hisan.freeride.common.view.MikyouLetterListView;
import com.hisan.freeride.databinding.ActivityAddresslistBinding;
import com.hisan.freeride.home.adapter.TestContactListAdapter;
import com.hisan.freeride.home.model.ContactBean;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.lzy.okgo.OkGo;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;


/**
 * 创建时间 : 2017/6/12
 * 创建人：yangyingqi
 * 公司：嘉善和盛网络有限公司
 * 备注：自定义手机通讯录
 */

public class AddressListActivity extends BaseActivity<ActivityAddresslistBinding> implements TestContactListAdapter.OnGetAlphaIndexerAndSectionsListener,PermissionListener{
    private List<ContactBean> mContactBeanList;//所有联系人集合
    private ListView mContactListView;//联系人ListView
    private TextView overLayout;//弹出对话框
    private OverlayThread overlayThread;
    private Map<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
    private Handler handler;
    private TestContactListAdapter adapter;
    private Intent intent;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_addresslist;
    }


    @Override
    protected void initView() {
        mBinding.setStateModel(mStateModel);
        if(Build.VERSION.SDK_INT >= 23){
            if (Dexter.isRequestOngoing()) {
                return;
            }
            //动态申请权限
            Dexter.checkPermission(this, Manifest.permission.GET_ACCOUNTS);
        }else {
            mContactListView = (ListView) findViewById(R.id.id_listview);
            handler=new Handler();
            overlayThread=new OverlayThread();
            ContactInfoService mContactInfoService=new ContactInfoService(this);
            mContactBeanList=mContactInfoService.getContactList();//返回手机联系人对象集合
            if (!CollectionUtils.isNullOrEmpty(mContactBeanList)){
                showData();
                //按拼音首字母表排序
                Collections.sort(mContactBeanList,comparator);
                initOverlay();
                registerAllViewAdapters();
            }else{
                noData();
            }
        }
    }

    @Override
    protected void initEvent() {
        findViewById(R.id.top_back).setOnClickListener(v -> finishActivity(true));

        mContactListView.setOnItemClickListener((parent, view, position, id) -> {
            TextView tname= (TextView) view.findViewById(R.id.contact_title);
            TextView tnumber= (TextView) view.findViewById(R.id.contact_phone_num);
            SaveContact(tname,tnumber);
        });
    }

    @Override
    protected void loadData(boolean isRefresh) {

    }


    //添加紧急联系人
    private void SaveContact(TextView tname, TextView tnumber) {

        OkGo.post(AppConfig.SaveContact)
                .tag(this)
                .params("name",tname.getText().toString())
                .params("mobile",tnumber.getText().toString())
                .execute(new DialogCallback<Object>(this) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<Object> response) {
                        super.onSuccess(response);
                        if (CollectionUtils.isNullOrEmpty(intent))intent=new Intent();
                        setResult(99,intent);
                        finishActivity(true);
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<Object> response) {
                        super.onError(response);
                        showError(response);
                    }
                });


    }
    private void registerAllViewAdapters() {
        adapter=new TestContactListAdapter(this,mContactBeanList, R.layout.contact_list_item);
        adapter.setOnGetAlphaIndeserAndSectionListener(this);
        mContactListView.setAdapter(adapter);
    }





    @Override
    public void getAlphaIndexerAndSectionsListner(Map<String, Integer> alphaIndexer, List<String> sections) {
        this.alphaIndexer=alphaIndexer;
//           this.sections=sections;
    }

    //用户允许权限
    @Override
    public void onPermissionGranted(PermissionGrantedResponse response) {
        showToast("开启权限成功");
    }
    //用户不允许权限
    @Override
    public void onPermissionDenied(PermissionDeniedResponse response) {
        showDeniedDialog();
    }
    //用户不允许权限，向用户解释权限左右
    @Override
    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
        showRationaleShouldBeShownDialog(token);
    }

    /**
     * 用户不允许权限，向用户说明权限的重要性，并支持用户去设置中开启权限
     */
    private void showDeniedDialog(){
        new AlertDialog.Builder(this).setTitle("请允许读取手机通讯录")
                .setMessage("无法获取此权限，不能正常工作")
                .setNegativeButton("拒绝", (dialog, which) -> dialog.dismiss())
                .setPositiveButton("去设置", (dialog, which) -> {
                    Intent intent1 = new Intent();
                    intent1.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    intent1.setData(Uri.parse("package:"+getPackageName()));
                    intent1.putExtra("cmp", "com.android.settings/.applications.InstalledAppDetails");
                    intent1.addCategory("android.intent.category.DEFAULT");
                    startActivity(intent1);
                    dialog.dismiss();
                })
                .show();
    }
    /**
     * 用户不允许权限，向用户说明权限的重要性
     * @param token
     */
    private void showRationaleShouldBeShownDialog(final PermissionToken token){
        new AlertDialog.Builder(this).setTitle("提示")
                .setMessage("获取读取手机通讯录权限，不开启将无法读取手机通讯录！")
                .setNegativeButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                    token.cancelPermissionRequest();
                })
                .setPositiveButton("确定", (dialog, which) -> {
                    dialog.dismiss();
                    token.continuePermissionRequest();
                })
                .setOnDismissListener(dialog -> token.cancelPermissionRequest())
                .show();
    }

    /**
     * @Mikyou
     * 字母列表点击滑动监听器事件
     * */
    private class LetterListViewListener implements
            MikyouLetterListView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            if (alphaIndexer.get(s) != null) {//判断当前选中的字母是否存在集合中
                int position = alphaIndexer.get(s);//如果存在集合中则取出集合中该字母对应所在的位置,再利用对应的setSelection，就可以实现点击选中相应字母，然后联系人就会定位到相应的位置
                mContactListView.setSelection(position);
                overLayout.setText(s);
                overLayout.setVisibility(View.VISIBLE);
                handler.removeCallbacks(overlayThread);
                // 延迟一秒后执行，让overlay为不可见
                handler.postDelayed(overlayThread, 1500);
            }
        }

    }
    /**
     * @mikyou
     * 初始化汉语拼音首字母弹出提示框
     * */
    private void initOverlay() {
        LayoutInflater inflater = LayoutInflater.from(this);
        overLayout = (TextView) inflater.inflate(R.layout.overlay, null);
        overLayout.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager =
                (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overLayout, lp);
    }
    /**
     * @Mikyou
     * 首字母按a-z排序
     * */
    Comparator<ContactBean> comparator=new Comparator<ContactBean>() {
        @Override
        public int compare(ContactBean t1, ContactBean t2) {
            String a=t1.getFirstHeadLetter();
            String b=t2.getFirstHeadLetter();
            int flag=a.compareTo(b);
            if (flag==0){
                return a.compareTo(b);
            }else{
                return flag;
            }
        }
    };
    /**
     * @Mikyou
     * 设置overlay不可见
     * */
    private class OverlayThread implements Runnable{

        @Override
        public void run() {
            overLayout.setVisibility(View.GONE);
        }
    }

}
